package cn.edu.sdjzu.cs.dingcan.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.sdjzu.cs.dingcan.entity.Customer;
import cn.edu.sdjzu.cs.dingcan.entity.DinnerTable;
import cn.edu.sdjzu.cs.dingcan.entity.Order;
import cn.edu.sdjzu.cs.dingcan.entity.ShoppingCart;
import cn.edu.sdjzu.cs.dingcan.service.OrderService;
import cn.edu.sdjzu.cs.dingcan.utils.PageBean;
import org.apache.commons.lang3.StringUtils;

@WebServlet("/order")
public class OrderServlet extends HttpServlet {
	/**
	 *
	 */
	private static final long serialVersionUID = -7159104050819049788L;

	private final OrderService orderService = new OrderService();

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = request.getParameter("method");
		if(StringUtils.isBlank(method)) {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "method参数未提供或为空");
			return;
		}
		switch (method) {
			case "take-order":
				try {
					this.takeOrder(request, response);
				} catch (SQLException throwables) {
					throwables.printStackTrace();
				}
				break;
			case "call":
				try {
					this.call(request, response);
				} catch (SQLException throwables) {
					throwables.printStackTrace();
				}
				break;
			case "get-orders":
				try {
					this.getOrderList(request, response);
				} catch (SQLException throwables) {
					throwables.printStackTrace();
				}
				break;
		}
	}
	
	

	//下单的方法
	public void takeOrder(HttpServletRequest request,
			HttpServletResponse response) throws IOException, SQLException {
		HttpSession session = request.getSession();

		ShoppingCart cart = (ShoppingCart) session.getAttribute(ShoppingCartServlet.CART_SESSION_KEY);
		Customer customer = (Customer) session.getAttribute("customer");
		this.orderService.takeOrder(customer, cart);

		String uri = request.getContextPath() + "/app/detail/clientOrderList.jsp";
		response.sendRedirect(uri);
	}

//	public void findOrder(HttpServletRequest request,
//			HttpServletResponse response) throws ServletException, IOException, SQLException {
//		List<Order> orders = orderService.getAllOrders();
//		// List<OrderDetail> orderDetail = orderDetailService.query();
//		this.getServletContext().setAttribute("orders", orders);
//		// this.getServletContext().setAttribute("orderDetail", orderDetail);
//	}

	// public Object getOrderDetail(HttpServletRequest request,
	// 		HttpServletResponse response) throws ServletException, IOException {
	// 	Object uri = null;
	// 	String id = request.getParameter("orderId");
	// 	List<OrderDetail> list = null;
	// 	if (id != null && !id.isEmpty()) {
	// 		list = orderDetailService.findByOrderId(Integer.parseInt(id));
	// 	}

	// 	request.setAttribute("orderDetail", list);

	// 	uri = request.getRequestDispatcher("/sys/order/orderDetail.jsp");
	// 	return uri;
	// }

	// 后台结账的方法
	public void pay(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {
//		DinnerTableService tableService = new DinnerTableService();
		Long orderId = Long.parseLong(request.getParameter("orderId"));			
		Long tableId = Long.parseLong(request.getParameter("tableId"));

		orderService.checkout(orderId, tableId);
//		findOrder(request, response);

//		DinnerTable table = tableService.findById(tableId);// 用于后台点击结账时消除通知
		@SuppressWarnings("unchecked")
		List<String> list = (List<String>) this.getServletContext()
				.getAttribute("tn");
//		if (list != null) {
//			list.remove(table.getTableName());
//		}
		getOrderList(request, response);
		// 跳转
		request.getRequestDispatcher("sys/order/orderList.jsp").forward(request, response);;
	}

	// 前台呼叫结账的方法
	public void call(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, NumberFormatException, SQLException {
//		DinnerTableService tableService = new DinnerTableService();
		HttpSession session = request.getSession();
		Long tableId = (Long) session.getAttribute("table_id");
//		DinnerTable table = tableService.findById(tableId);

//		String tableName = table.getTableName();

		@SuppressWarnings("unchecked")
		List<String> waitingForCheckout = (List<String>) this.getServletContext()
				.getAttribute("tn");
		if (waitingForCheckout == null) {
			waitingForCheckout = new ArrayList<>();
		}
//		waitingForCheckout.add(tableName);

		this.getServletContext().setAttribute("tn", waitingForCheckout);

//		List<DinnerTable> tables = tableService.findAll();// 更新前台首页的桌子
//		this.getServletContext().setAttribute("table-list", tables);

		String uri = request.getContextPath() + "/index";

		response.sendRedirect(uri);
	}

	public void getOrderList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SQLException {
		//  获取“当前页”参数； (第一次访问当前页为null)
		String currPage = request.getParameter("currentPage");
		// 判断
		if (currPage == null || "".equals(currPage.trim())) {
			currPage = "1"; // 第一次访问，设置当前页为1;
		}
		
		int currentPage = Integer.parseInt(currPage);

		//  创建PageBean对象，设置当前页参数； 传入service方法参数
		PageBean<Order> pageBean = new PageBean<>();
		pageBean.setCurrentPage(currentPage);
		pageBean.setPageCount(6);

		//  调用service
		orderService.getAllOrders(pageBean); // 【pageBean已经被dao填充了数据】
		//  保存pageBean对象，到request域中
		request.setAttribute("pageBean", pageBean);

		// 跳转
		request.getRequestDispatcher("/sys/order/orderList.jsp").forward(request, response);
	}

}
